package com.jt.www.biz.user_pc.controller;

import com.jt.www.admin.order_pc.service.ExportConfigService;
import com.jt.www.annotations.AvoidRepeatableCommit;
import com.jt.www.biz.user_pc.service.IndustryManagerService;
import com.jt.www.domain.dto.IndustryManagerDto;
import com.jt.www.domain.enums.common.ExportChannelTypeEnum;
import com.jt.www.domain.po.ExportConfigEntity;
import com.jt.www.domain.po.IndustryManager;
import com.jt.www.domain.qo.IndustryManagerQo;
import com.jt.www.domain.vo.IndustryManagerVo;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.util.excel.CsvExportUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * Created by shaoyn on 2020/12/09.
 */
@Api(value = "行管用户管理", tags = {"INDUSTRY-MANAGER"}, description = "行管用户管理")
@RestController
@RequestMapping(value = "/industryManager")
public class IndustryManagerController {

    public static final Logger log = LoggerFactory.getLogger(IndustryManagerController.class);
    @Autowired
    private IndustryManagerService industryManagerService;
    @Autowired
    private ExportConfigService exportConfigService;

    @ApiOperation(value = "添加行管用户", httpMethod = "POST")
    @PostMapping(value = "/addIndustryManager", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    @AvoidRepeatableCommit
    public ResponseEntity addIndustryManager(@RequestBody IndustryManagerVo industryManagerVo) {
        if (null == industryManagerVo) {
            return GenericDataResponse.errorWithMsg("用户信息不能为空!");
        }
        if (StringUtils.isBlank(industryManagerVo.getAccount())) {
            return GenericDataResponse.errorWithMsg("帐号不能为空!");
        }
        if (StringUtils.isBlank(industryManagerVo.getUserName())) {
            return GenericDataResponse.errorWithMsg("用户姓名不能为空!");
        }
        if (StringUtils.isBlank(industryManagerVo.getOrgName())) {
            return GenericDataResponse.errorWithMsg("机构名称不能为空!");
        }
        if (StringUtils.isBlank(industryManagerVo.getBranchCode())) {
            return GenericDataResponse.errorWithMsg("分支机构不能为空!");
        }

        String findCode = "addIndustryManager_" + System.currentTimeMillis();
        try {
            return industryManagerService.addIndustryManager(findCode, industryManagerVo);
        } catch (Exception e) {
            log.info("{} 添加行管用户", findCode, e);
            return GenericDataResponse.errorWithMsg(e.getMessage());
        }
    }

    @ApiOperation(value = "修改行管用户", httpMethod = "POST")
    @PostMapping(value = "/updateIndustryManager", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    @AvoidRepeatableCommit
    public ResponseEntity updateIndustryManager(@RequestBody IndustryManager industryManager) {
        if (null == industryManager || null == industryManager.getId()) {
            return GenericDataResponse.errorWithMsg("用户信息不能为空!");
        }
        String findCode = "updateIndustryManager_" + System.currentTimeMillis();
        try {
            return industryManagerService.updateIndustryManager(findCode, industryManager);
        } catch (Exception e) {
            log.info("{} 修改行管用户", findCode, e);
            return GenericDataResponse.errorWithMsg(e.getMessage());
        }
    }


    @ApiOperation(value = "修改行管用户状态", httpMethod = "GET")
    @GetMapping(value = "/updateIndustryManagerStatus", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    @AvoidRepeatableCommit
    public ResponseEntity updateIndustryManagerStatus(@ApiParam(value = "产品配置表id", required = true) @RequestParam Long id,
                                                      @ApiParam(value = "产品编码", required = true) @RequestParam Byte status) {
        String findCode = "updateIndustryManagerStatus_" + System.currentTimeMillis();
        try {
            return industryManagerService.updateIndustryManagerStatus(findCode, id, status);
        } catch (Exception e) {
            log.info("{} 修改行管用户失败", findCode, e);
            return GenericDataResponse.errorWithMsg(e.getMessage());
        }
    }

    @ApiOperation(value = "行管用户列表", httpMethod = "POST")
    @PostMapping(value = "/queryIndustryManager", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity<GenericListResponse<IndustryManagerDto>> queryIndustryManager(@RequestBody IndustryManagerQo industryManagerQo) {
        String findCode = "queryIndustryManager_" + System.currentTimeMillis();
        return industryManagerService.queryIndustryManager(findCode, industryManagerQo);
    }

    @ApiOperation(value = "导出行管用户列表", notes = "导出行管用户列表")
    @GetMapping(value = "/downIndustryManager", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public void downIndustryManager(IndustryManagerQo industryManagerQo, HttpServletResponse response) {
        String findCode = "EDU_downIndustryManager_" + System.currentTimeMillis();
        OutputStream os = null;
        try {
            //查询导出配置
            ExportConfigEntity exportConfigEntity = exportConfigService.getExportConfig(ExportChannelTypeEnum.INDUSTRY_MANAGER.getCode());
            if (null == exportConfigEntity) {
                return;
            }
            String fileName = exportConfigEntity.getFileName();

            os = response.getOutputStream();
            CsvExportUtil.responseSetProperties(fileName, response);
            //模板位置
            String titles = exportConfigEntity.getTitles();
            CsvExportUtil.setTitles(titles, os);
            List<IndustryManagerDto> appList;
            int pn = 1;
            industryManagerQo.setPn(pn);
            industryManagerQo.setPs(CsvExportUtil.MAX_PAGE_SIZE);
            String[] keyArr = exportConfigEntity.getKeyArr().split(",");

            //分批查询并生成数据插入到导出文件中
            while (CollectionUtils.isNotEmpty(appList = industryManagerService.queryIndustryManager(findCode, industryManagerQo).getBody().getList())) {
                // List list = Lists.transform(appList, (Function<IndustryManagerDto, Object>) commissionPush -> new CommissionPushDownDTO(commissionPush));
                CsvExportUtil.doExport(appList, keyArr, os);
                industryManagerQo.setPn(++pn);
                if (industryManagerQo.getPs() > appList.size()) {
                    break;
                }
            }
        } catch (Exception e) {
            log.error("{}导出{}发生错误:", findCode, e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                }
            }
        }
    }


}
